#include <iostream>
#include <string>
#include "/home/lhr/http-server/dbManager.hpp"
#include "/home/lhr/http-server//Util.hpp"
#include <jsoncpp/json/json.h>

int main()
{
    // 获取请求参数
    std::string reqParam;
    Util::GetReqParam(reqParam);

    // 拆分请求参数
    std::string str1, str2;
    Util::CutString(reqParam, str1, str2, "&");

    std::string usrName, username;
    Util::CutString(str1, usrName, username, "=");
    username = Util::UrlDecode(username);
    
    std::string usrPasswd, password;
    Util::CutString(str2, usrPasswd, password, "=");

    // 获取数据库单例并进行注册操作
    DBManager &db = DBManager::GetInstance();
    int ret = db.RegisterUser(username, password);

    // 构建 JSON 响应
    Json::Value response;
    if (ret == 0) // 注册成功
    {
        response["success"] = true;
        response["message"] = "注册成功";
    }
    else if (ret == USR_EXISTS) // 用户名已存在
    {
        response["success"] = false;
        response["message"] = "用户名已存在";
    }
    else // 服务器内部错误
    {
        response["success"] = false;
        response["message"] = "服务器错误，请稍后重试";
    }

    // JSON 响应体
    std::string http_resBody = response.toStyledString();

    // 构建 HTTP 响应头
    std::string http_res;
    http_res += "HTTP/1.0 200 OK\r\n";
    http_res += "Content-Type: application/json\r\n";
    http_res += "Content-Length: " + std::to_string(http_resBody.length()) + "\r\n";
    http_res += "\r\n"; // 空行分隔头部和正文
    http_res += http_resBody;

    // 输出 HTTP 响应到管道
    std::cout << http_res;

    return 0;
}
